package it.polimi.reTraveldream.eao;

import it.polimi.reTravelDream.dto.CityDTO;
import it.polimi.reTravelDream.dto.UserDTO;
import it.polimi.reTravelDream.eao.UserEAOLocal;
import it.polimi.reTraveldream.ejb.usermanager.Group;
import it.polimi.reTraveldream.ejb.usermanager.UsersEntity;
import it.polimi.reTraveldream.entities.City;
import it.polimi.reTraveldream.entities.Flight;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.sun.tools.xjc.reader.xmlschema.bindinfo.BIConversion.User;

/**
 * Session Bean implementation class UserEAO
 */
@Stateless
public class UserEAO implements UserEAOLocal {


	@PersistenceContext
    private EntityManager em;
	
    public UserEAO() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void add(UserDTO userDTO) {
		UsersEntity newUser= new UsersEntity (userDTO);
		List<Group> groups = new ArrayList<Group>();
		groups.add(Group.USER);
		newUser.setGroups(groups);
		em.persist(newUser);
	}
	
	@Override
	public UserDTO getUser(String email) {
		UserDTO userDTO=new UserDTO();
		
		UsersEntity usersEntity=em.find(UsersEntity.class, email);		
		userDTO=this.convertToDTO(usersEntity);
		return userDTO;
	}
	
	private UserDTO convertToDTO(UsersEntity usersEntity){
		UserDTO userDTO=new UserDTO();
		userDTO.setEmail(usersEntity.getEmail());
		userDTO.setFirstName(usersEntity.getFirstName());
		userDTO.setLastName(usersEntity.getLastName());
		return userDTO;
	}

	@Override
	public List<UserDTO> getAllUser() {
		List<UsersEntity> resultEntities= em.createNamedQuery(UsersEntity.FIND_ALL, UsersEntity.class)
                .getResultList();
		 List<UserDTO> resultDTO= new ArrayList<UserDTO>();
		 for (UsersEntity u: resultEntities){
			 resultDTO.add(convertToDTO(u));
		 }
		 return resultDTO;
	}

	@Override
	public void delete(UserDTO userDTO) {
		// TODO Auto-generated method stub
		
	}
	

	
}
